<template>
  <div class="container">
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="科室">
          <el-cascader
            v-model="searchForm.deptId"
            :options="departmentOptions"
            :props="{ 
              checkStrictly: true,
              value: 'id',
              label: 'departmentName',
              children: 'children'
            }"
            placeholder="请选择科室"
            clearable
          />
        </el-form-item>
        <el-form-item label="职称">
          <el-select v-model="searchForm.jobTitleId" placeholder="请选择职称" style="width: 100%">
            <el-option v-for="item in titleOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">筛选</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="table-header">
        <el-button type="danger" :disabled="selectedDoctors.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>
      
      <el-table 
        :data="doctorList" 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="doctorName" label="姓名" width="120" />
        <el-table-column prop="mobile" label="电话" width="150" />
        <el-table-column prop="hospitalName" label="医院" />
        <el-table-column prop="departmentName" label="科室" width="120" />
        <el-table-column prop="jobTitleName" label="职称" width="120" />
        <el-table-column prop="status" label="审核状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button size="small" @click="viewDoctor(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editDoctor(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="searchForm.pageSize"
          :current-page="searchForm.pageIndex"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDoctors, getDepartmentsCascade } from '@/http/axiosRead'
import { deleteDoctor, batchDeleteDoctors } from '@/http/axiosWrtie'

interface Doctor {
  id: number;
  doctorName: string;
  mobile: string;
  hospitalName: string;
  departmentName: string;
  jobTitleName: string;
  status: string;
  [key: string]: any;
}

const searchForm = reactive({
  doctorName: '',
  deptId: undefined,
  jobTitleId: undefined,
  pageIndex: 1,
  pageSize: 10
})

const doctorList = ref<Doctor[]>([])
const total = ref(0)
const departmentOptions = ref([])
const selectedDoctors = ref<Doctor[]>([])
const titleOptions = ref([
  { id: 1, name: '主任医师' },
  { id: 2, name: '副主任医师' },
  { id: 3, name: '主治医师' },
  { id: 4, name: '住院医师' },
  { id: 5, name: '药剂师' },
  { id: 6, name: '护士' }
])

onMounted(() => {
  fetchDepartmentList()
  fetchDoctorList()
})

const fetchDepartmentList = async () => {
  try {
    const response = await getDepartmentsCascade()
    if (response.data && response.data.data && response.data.data.departments) {
      departmentOptions.value = response.data.data.departments
    }
  } catch (error) {
    console.error('获取科室列表失败：', error)
    ElMessage.error('获取科室列表失败')
  }
}

const fetchDoctorList = async () => {
  try {
    const response = await getDoctors(searchForm)
    doctorList.value = response.data.pageData || []
    total.value = response.data.totaCount || 0
  } catch (error) {
    console.error('获取医生列表失败：', error)
    ElMessage.error('获取医生列表失败')
  }
}

const handleSelectionChange = (selection: Doctor[]) => {
  selectedDoctors.value = selection
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除医生 ${row.doctorName}？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteDoctor(row.id)
      if (response.data && response.data.code === 200) {
        ElMessage.success('删除成功')
        fetchDoctorList()
      } else {
        ElMessage.error(response.data?.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除医生失败：', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消删除，不做处理
  })
}

const handleBatchDelete = () => {
  if (selectedDoctors.value.length === 0) {
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedDoctors.value.length} 名医生？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedDoctors.value.map(doctor => doctor.id as number)
      const response = await batchDeleteDoctors(ids)
      if (response.data && response.data.code === 200) {
        ElMessage.success('批量删除成功')
        fetchDoctorList()
      } else {
        ElMessage.error(response.data?.msg || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除医生失败：', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消删除，不做处理
  })
}

const onSearch = () => {
  searchForm.pageIndex = 1
  fetchDoctorList()
}

const resetForm = () => {
  searchForm.doctorName = ''
  searchForm.deptId = undefined
  searchForm.jobTitleId = undefined
  onSearch()
}

const handleSizeChange = (val: number) => {
  searchForm.pageSize = val
  fetchDoctorList()
}

const handleCurrentChange = (val: number) => {
  searchForm.pageIndex = val
  fetchDoctorList()
}

const getStatusType = (status: string) => {
  switch (status) {
    case '已通过':
      return 'success'
    case '未通过':
      return 'danger'
    case '未审核':
    default:
      return 'info'
  }
}

const getStatusText = (status: string) => {
  return status || '未审核'
}

const viewDoctor = (row: any) => {
  ElMessage.info(`查看医生：${row.doctorName}`)
}

const editDoctor = (row: any) => {
  ElMessage.info(`编辑医生：${row.doctorName}`)
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.table-container {
  margin-top: 20px;
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 